package com.review.aop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.review.aop.common.constant.Constants;
import com.review.aop.common.util.JwtUtil;
import com.review.aop.domain.UserInfo;
import com.review.aop.domain.vo.UserLoginVO;
import com.review.aop.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public boolean login(String userName, String password, HttpServletRequest request) {
        UserInfo userInfo = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUsername, userName)
                        .eq(UserInfo::getDeleteFlag,0)
                .select(UserInfo::getId, UserInfo::getUsername, UserInfo::getPassword));
        if (userInfo==null || !password.equals(userInfo.getPassword())){
            log.error("用户账号错误或者密码错误");
            return false;
        }
        HttpSession session = request.getSession(true);
        request.setAttribute(Constants.USER_SESSION,userInfo);
        return true;
    }

    public UserLoginVO loginByToken(String userName, String password) {
        UserInfo userInfo = userMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUsername, userName)
                .eq(UserInfo::getDeleteFlag,0)
                .select(UserInfo::getId, UserInfo::getUsername, UserInfo::getPassword));
        if (userInfo==null || !password.equals(userInfo.getPassword())){
            log.error("用户账号错误或者密码错误");
            return new UserLoginVO();
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userInfo.getId());
        claims.put("username",userInfo.getUsername());
        String token = JwtUtil.createToken(claims, Constants.SECRET);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setIsLogin(true);
        userLoginVO.setToken(token);
        return userLoginVO;
    }
}
